package top.crossrun.notify;

import android.app.Notification;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;

public class MyNotificationListenerService extends NotificationListenerService {

    public static final String ACTION = "MyNotificationListenerService.Broadcast";

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        if (getPackageName().equals(sbn.getPackageName())) {
            return;
        }

        if ("android".equals(sbn.getPackageName())) {
            return;
        }

        StringBuilder sb = new StringBuilder();
        Bundle extras = sbn.getNotification().extras;
        {
            CharSequence s = extras.getCharSequence(Notification.EXTRA_TITLE);
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                sb.append("-");
            }
        }
        {
            CharSequence s = extras.getCharSequence(Notification.EXTRA_TEXT);
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                sb.append("-");
            }
        }
        {
            CharSequence s = extras.getCharSequence(Notification.EXTRA_SUB_TEXT);
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                sb.append("-");
            }
        }
        {
            CharSequence s = extras.getCharSequence(Notification.EXTRA_INFO_TEXT);
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                sb.append("-");
            }
        }
        {
            CharSequence s = sbn.getTag();
            if (!TextUtils.isEmpty(s)) {
                sb.append(s);
                sb.append("-");
            }
        }
        Intent data = new Intent(ACTION);
        data.putExtra("tag", "通知");
        data.putExtra("src", getLable(sbn.getPackageName()));
        data.putExtra("message", sb.toString());
        LocalBroadcastManager.getInstance(this).sendBroadcast(data);
    }

    private String getLable(String pakgename) {
        PackageManager pm = getPackageManager();
        try {
            ApplicationInfo appInfo = pm.getApplicationInfo(pakgename, PackageManager.GET_META_DATA);
            return pm.getApplicationLabel(appInfo).toString();
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

}
